package com.ryandj.controller.user;

import com.alibaba.fastjson.JSON;
import com.ryandj.dto.UserDTO;
import com.ryandj.exMessage.OOTDException;
import com.ryandj.exMessage.LoginErrMsg;
import com.ryandj.result.WebResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by wdj on 2024/6/3
 */

@RestController
@RequestMapping("/user")
@Api("用户相关接口")
@Slf4j
public class UserController {


    @PostMapping("/login")
    @ApiOperation("用户登录")
    public WebResult login(@RequestBody UserDTO userDTO){

        log.info("UserController#login，用户登录,user={}", JSON.toJSON(userDTO));

        if(StringUtils.isEmpty(userDTO.getUsername())){
            throw new OOTDException(LoginErrMsg.USER_NAME_EMPTY.getCode(), LoginErrMsg.USER_NAME_EMPTY.getMessage());
        }

        if(StringUtils.isEmpty(userDTO.getPassword())){
            throw new OOTDException(LoginErrMsg.USER_PASSWORD_EMPTY.getCode(), LoginErrMsg.USER_PASSWORD_EMPTY.getMessage());
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userDTO.getUsername(), userDTO.getPassword());
        try {
            subject.login(token);
        }catch (Exception e){
            throw new OOTDException(LoginErrMsg.INVALID_PASSWORD.getCode(), LoginErrMsg.INVALID_PASSWORD.getMessage());
        }

        return WebResult.success();
    }

}
